const { commonWords } = require("./commonWords");

function getMiddleThreeElements(arr, maxWords) {
  if (!Array.isArray(arr) || arr.length === 0) {
    return [];
  }

  if (arr.length <= maxWords) {
    return [...arr]; // 返回数组的副本
  }

  const middleIndex = Math.floor(arr.length / 2);
  const halfMax = Math.round(maxWords / 2);

  return arr.slice(middleIndex - halfMax, middleIndex + halfMax);
}
/**
 * 提取关键词（简单实现：提取句子中的主要单词）
 * @param {string} text - 输入文本
 * @returns {string} 关键词
 */
function extractKeywords(text, maxWords) {
  // 移除标点符号和多余空格
  const cleanText = text.replace(/[^\w\s\u4e00-\u9fff]/gi, "").trim();

  // 提取英文单词
  const englishWords = cleanText.match(/[a-zA-Z]+/g) || [];

  // 优先使用英文单词
  if (englishWords.length > 0) {
    const filteredWords = englishWords.filter(word => word.length > 2 && !commonWords.includes(word.toLowerCase()));
    if (filteredWords.length > 0) {
      let result = getMiddleThreeElements(filteredWords, maxWords);
      result = result.filter((item, index) => result.indexOf(item) === index).join(" ");
      return result;
    }
  }
  return ["peace", "love"].join(" ");
}

/**
 * 标准化关键词（用于比较相似性）
 * @param {string} keywords - 原始关键词
 * @returns {string} 标准化后的关键词
 */
function normalizeKeywords(keywords) {
  return keywords.toLowerCase().replace(/\s+/g, " ").trim();
}

/**
 * 检查关键词是否相似
 * @param {string} keyword1 - 关键词1
 * @param {string} keyword2 - 关键词2
 * @returns {boolean} 是否相似
 */
function areKeywordsSimilar(keyword1, keyword2) {
  const normalized1 = normalizeKeywords(keyword1);
  const normalized2 = normalizeKeywords(keyword2);

  // 如果完全相同，则相似
  if (normalized1 === normalized2) {
    return true;
  }

  // 检查是否包含关系
  if (normalized1.includes(normalized2) || normalized2.includes(normalized1)) {
    return true;
  }

  // 检查单词重叠
  const words1 = normalized1.split(" ");
  const words2 = normalized2.split(" ");

  const commonWords = words1.filter(word => words2.includes(word));
  return commonWords.length > 0;
}

module.exports = {
  extractKeywords,
  normalizeKeywords,
  areKeywordsSimilar,
};
